package com.newly.gateway.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.newly.common.base.constants.ServerUriConstant;
import com.newly.common.base.entity.R;
import com.newly.common.core.utils.NewlyCommonUtils;
import com.newly.gateway.service.api.ILoginRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: newly-parent
 * @description: 登录历史
 * @author: guan
 * @create: 2022-02-18 10:16
 */
@Service
@Slf4j
public class LoginRecord implements ILoginRecord {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean generate(ServerWebExchange exchange, String username, boolean loginStatus) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        Map<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("status", loginStatus ? "1" : "0");
        try {
            HttpEntity httpEntity = new HttpEntity<>(params, request.getHeaders());
            ResponseEntity<R> responseEntity = restTemplate.exchange(ServerUriConstant.NEWLY_SYS_LOGIN_RECORD_URI + "/create",
                    HttpMethod.POST, httpEntity, R.class);
            // 校验是否通过
            if (!ObjectUtil.isEmpty(responseEntity)) {
                R r = responseEntity.getBody();
                return (boolean) r.getData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
